package com.stockz.downloader.breadth.bse;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;

import org.springframework.util.StringUtils;

import com.stockz.equity.model.Bar;

public class BseBarSpanCSVParser {

	public static List<Bar> parseCsv(String s){
		List<Bar> barList = new ArrayList<Bar>();
		if(StringUtils.hasText(s)){
			StringTokenizer t = new StringTokenizer(s,"\n",false);
			while(t.hasMoreTokens()){
				Bar b = parseString(t.nextToken());
				if(b != null){
					barList.add(b);					
				}
			}
		}
		return barList;
	}
	
	@SuppressWarnings("deprecation")
	public static Bar parseString(String str){
		Bar bar = new Bar();
		if(StringUtils.hasText(str)){
			StringTokenizer t = new StringTokenizer(str.substring(str.indexOf(":")+1),",");
			try{
				String date = t.nextToken();
				Date d = new Date();
				String[] tokens = date.split("/");
				d.setMonth(Integer.parseInt(tokens[0])-1);
				d.setDate(Integer.parseInt(tokens[1]));
				d.setYear(Integer.parseInt(tokens[2])-1900);
				bar.setDate(d);
				
				bar.setOpen(Double.parseDouble(t.nextToken()));
				bar.setHigh(Double.parseDouble(t.nextToken()));
				bar.setLow(Double.parseDouble(t.nextToken()));
				bar.setClose(Double.parseDouble(t.nextToken()));
				bar.setVolume(Double.parseDouble(t.nextToken()));
			}catch(Exception e){
				bar = null;
			}
		}
		return bar;
	}
	
}
